﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using ArsenalManagement.Models;
using Microsoft.AspNetCore.Mvc.Filters;
using ArsenalManagement.Tools;

namespace ArsenalManagement.Controllers
{
    public class WeaponController : Controller
    {
        private readonly ArsenalManagementContext _context;

        public WeaponController(ArsenalManagementContext context)
        {
            _context = context;
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            string id = HttpContext.Session.GetString("user");
            if (string.IsNullOrEmpty(id))
            {
                context.Result = new RedirectResult("../User/Login");
            }
            else
            {
                ViewData["username"] = id;
            }
            base.OnActionExecuting(context);
        }

        public async Task<IActionResult> Index(
        string sortOrder,
        string currentFilter,
        string searchString,
        int? page)
        {
            ViewData["CurrentSort"] = sortOrder;
            ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewData["InfoSortParm"] = sortOrder == "info_asc" ? "info_desc" : "info_asc";
            //String.IsNullOrEmpty(sortOrder) ? "info_desc" : "info_asc";

            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewData["CurrentFilter"] = searchString;

            var weapons = from s in _context.Weapons
                           select s;
            if (!String.IsNullOrEmpty(searchString))
            {
                weapons = weapons.Where(s => s.Weaponname.Contains(searchString)
                                       || s.Info.Contains(searchString));
            }
            switch (sortOrder)
            {
                case "name_desc":
                    weapons = weapons.OrderByDescending(s => s.Weaponname);
                    break;
                case "info_desc":
                    weapons = weapons.OrderByDescending(s => s.Info);
                    break;
                case "info_asc":
                    weapons = weapons.OrderBy(s => s.Info);
                    break;
                default:
                    weapons = weapons.OrderBy(s => s.Weaponname);
                    break;
            }
            //页面大小
            int pageSize = 5;
            return View(await PaginatedList<Weapon>.CreateAsync(weapons.AsNoTracking(), page ?? 1, pageSize));
        }

        // GET: Weapon
        //public async Task<IActionResult> Index()
        //{
        //      return _context.Weapons != null ? 
        //                  View(await _context.Weapons.ToListAsync()) :
        //                  Problem("Entity set 'ArsenalManagementContext.Weapons'  is null.");
        //}

        // GET: Weapon/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null || _context.Weapons == null)
            {
                return NotFound();
            }

            var weapon = await _context.Weapons
                .FirstOrDefaultAsync(m => m.Id == id);
            if (weapon == null)
            {
                return NotFound();
            }

            return View(weapon);
        }

        // GET: Weapon/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Weapon/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,Weaponname,ImgUrl,Info")] Weapon weapon)
        {
            if (ModelState.IsValid)
            {
                _context.Add(weapon);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(weapon);
        }

        // GET: Weapon/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null || _context.Weapons == null)
            {
                return NotFound();
            }

            var weapon = await _context.Weapons.FindAsync(id);
            if (weapon == null)
            {
                return NotFound();
            }
            return View(weapon);
        }

        // POST: Weapon/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("Id,Weaponname,ImgUrl,Info")] Weapon weapon)
        {
            if (id != weapon.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(weapon);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!WeaponExists(weapon.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(weapon);
        }

        // GET: Weapon/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null || _context.Weapons == null)
            {
                return NotFound();
            }

            var weapon = await _context.Weapons
                .FirstOrDefaultAsync(m => m.Id == id);
            if (weapon == null)
            {
                return NotFound();
            }

            return View(weapon);
        }

        // POST: Weapon/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            if (_context.Weapons == null)
            {
                return Problem("Entity set 'ArsenalManagementContext.Weapons'  is null.");
            }
            var weapon = await _context.Weapons.FindAsync(id);
            if (weapon != null)
            {
                _context.Weapons.Remove(weapon);
            }
            
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool WeaponExists(int id)
        {
          return (_context.Weapons?.Any(e => e.Id == id)).GetValueOrDefault();
        }
    }
}
